package com.pcbly.web.components.interceptor;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.pcbly.web.bean.user.UserCookie;
import com.pcbly.web.config.SysConfig;

public class UserCookieInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3392580175115681320L;
	private static final Log logger = LogFactory
			.getLog(UserCookieInterceptor.class);

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		ActionContext ac = invocation.getInvocationContext();
		Object action = invocation.getAction();
		if (action instanceof UserCookieAware) {
			HttpServletRequest request = (HttpServletRequest) ac
					.get(ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ac
					.get(ServletActionContext.HTTP_RESPONSE);
			ServletContext servletContext = (ServletContext) ac
					.get(ServletActionContext.SERVLET_CONTEXT);
			WebApplicationContext wc = WebApplicationContextUtils
					.getWebApplicationContext(servletContext);
			if (wc == null) {
				logger.error("ApplicationContext could not be found.");
			} else {
				SysConfig sysConfig = (SysConfig) wc.getBean("sysConfig");
				if (!(sysConfig == null)) {
					UserCookie userCookie = new UserCookie(request, response,
							sysConfig);
					logger.debug("userCookie  id:" + userCookie.getId());
					((UserCookieAware) action).setUserCookie(userCookie);
				}
			}
		}
		return invocation.invoke();
	}

}
